Mason's Blog

High Performance JavaScript

Published 3 months ago5 min read4 comments

Why JavaScript Performance Still Matters

With the rise of single‑page applications and complex client‑side logic, JavaScript has become the backbone of user interaction. However, poorly optimized code can lead to janky scrolling, unresponsive buttons, and frustrated users. Studies show that a 100‑millisecond delay in load time can reduce conversion rates by 7%. High‑performance JavaScript isn’t just a nice‑to‑have—it’s a business necessity. Let’s dive into actionable strategies you can implement today.


1. Minimize DOM Access and Manipulation

The Document Object Model (DOM) is one of the slowest parts of browser rendering. Every read or write forces layout recalculations. To stay fast, batch DOM updates and use modern APIs like documentFragment or innerHTML sparingly. For example, instead of updating a list item by item in a loop, build the entire HTML string first and insert it once.

						
// Slow: 100 individual DOM writes
for (let i = 0; i < 100; i++) {
	const li = document.createElement('li');
	li.textContent = `Item ${i}`;
	list.appendChild(li);
}

// Fast: batch with fragment
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
	const li = document.createElement('li');
	li.textContent = `Item ${i}`;
	fragment.appendChild(li);
}
list.appendChild(fragment); // single reflow
						
					

2. Leverage Event Delegation

Attaching individual event listeners to dozens of similar elements (like table rows or menu items) consumes memory and initialization time. Event delegation takes advantage of event bubbling: attach one listener to a parent and inspect event.target. This is especially useful for dynamic content.


// Instead of:
document.querySelectorAll('.btn').forEach(btn => {
	btn.addEventListener('click', handleClick);
});

// Do:
document.addEventListener('click', (e) => {
	if (e.target.matches('.btn')) handleClick(e);
});
					

3. Optimize Loops and Conditionals

Loops are performance hot‑spots. Reduce work inside loops by caching array lengths and avoiding function calls that run repeatedly. Also, prefer for loops over forEach when every microsecond counts, though the difference is often negligible. Use break early when possible.


const items = getLargeArray();
// cache length
for (let i = 0, len = items.length; i < len; i++) {
	process(items[i]); // no repeated property lookup
}
					

4. Use requestAnimationFrame for Visual Updates

For animations and visual changes, setTimeout or setInterval can cause dropped frames. requestAnimationFrame synchronizes with the browser’s repaint cycle, ensuring smooth 60fps motion. Always schedule DOM changes inside a requestAnimationFrame callback.


function animate() {
	updatePosition(); // modifies element style
	requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
					

5. Eliminate Memory Leaks

Unused event listeners, detached DOM nodes, and forgotten timers keep memory from being garbage‑collected. In single‑page apps, clean up when components unmount. Use AbortController for fetch requests and remove event listeners with removeEventListener. Tools like Chrome DevTools heap snapshots help identify leaks.

🛠️ Quick win: Debounce or throttle expensive handlers like scroll and resize. A simple debounce ensures the callback runs only after the user stops firing the event.

6. Defer Non‑Critical JavaScript

Use async or defer attributes on script tags to avoid blocking DOM parsing. Also consider code‑splitting with tools like Webpack or Vite, so users only download what’s needed for the initial view. Lazy‑load heavy libraries and components until they’re required.


Conclusion

High‑performance JavaScript is a continuous discipline. Start by profiling your app with Lighthouse or the Performance panel; then apply the techniques above. Small, consistent optimizations add up to a noticeably faster experience. Remember: your users—and your metrics—will thank you. Happy coding!

Promo Section Heading

You can use this section to promote your side projects etc. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

Choose Colour